/* eslint-disable no-useless-return */
<template>
    <div>
      <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 用户列表 -->
        <el-card>
            <div>
              <!-- 搜索和添加功能 -->
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-input placeholder="请输入内容" clearable @clear='getUserList'  class="input-with-select" v-model="queryInfo.query">
                            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                        </el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="primary" size='medium' @click='dialogVisible = true'>添加</el-button>
                    </el-col>
                </el-row>
                <el-table border :data="userList" stripe style="width: 100%">
                  <el-table-column type='index'></el-table-column>
                  <el-table-column prop="username" label="姓名" width="180"></el-table-column>
                  <el-table-column prop="email" label="邮箱"></el-table-column>
                  <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
                  <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
                  <el-table-column label="状态">
                    <template v-slot:default="slotProps">
                    <el-switch v-model='slotProps.row.mg_state' @change="changeUserStatus(slotProps.row)"></el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width='180px'>
                    <template v-slot:default='slotProps'>
                      <!-- 修改按钮 -->
                      <el-button type="primary" size='mini' @click='editDialog(slotProps.row.id)' icon="el-icon-edit"></el-button>
                      <!-- 删除按钮 -->
                      <el-button type="danger" size='mini' icon="el-icon-delete" @click='removeUserById(slotProps.row.id)'></el-button>
                      <!-- 角色分配按钮 -->
                      <el-tooltip class="item" effect="dark" content="角色分配" :enterable='false' placement="top">
                        <el-button type="warning" size='mini' icon="el-icon-setting" @click='setRole(slotProps.row)'></el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="queryInfo.pagenum"
                  :page-sizes="[1,2,3,4,5,6]"
                  :page-size="queryInfo.pagesize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total">
                </el-pagination>

                <!-- 添加用户对话框 -->
                <el-dialog
                title="添加用户"
                :visible.sync="dialogVisible"
                width="50%"
                @close="handleClose">
                <span>
                  <el-form :model="addUserInfo" :rules="rules" ref="addUserFormRef" label-width="100px">
                    <el-form-item label="用户名" prop="username">
                      <el-input v-model="addUserInfo.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                      <el-input type='password' v-model="addUserInfo.password"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="addUserInfo.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" prop="mobile">
                      <el-input v-model="addUserInfo.mobile"></el-input>
                    </el-form-item>
                  </el-form>
                </span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="dialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
              </el-dialog>

              <!-- 编辑用户对话框 -->
              <el-dialog
                title="编辑用户"
                :visible.sync="editDialogVisible"
                width="50%"
                >
                <span>
                  <!-- 用户编辑表单 -->
                  <el-form :model="editUserFormData" :rules="editFormRules" ref="EditFormRef" label-width="100px">
                    <el-form-item label="用户名">
                      <el-input v-model="editUserFormData.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="editUserFormData.email"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                      <el-input v-model="editUserFormData.mobile"></el-input>
                    </el-form-item>
                  </el-form>
                </span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="editDialogVisible = false" @close='editDialogClose'>取 消</el-button>
                  <el-button type="primary" @click="editUserInfo">确 定</el-button>
                </span>
              </el-dialog>

              <!-- 角色分配对话框 -->
              <el-dialog
                title="角色分配"
                :visible.sync="setRoleDialogVisible"
                width="50%">
                <div>
                  <p>用户名:{{ userInfo.username }}</p>
                  <p>角色名称:{{ userInfo.role_name }}</p>
                  <p>
                    分配新角色:
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                      <el-option
                        v-for="item in roleList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </p>
                </div>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                  <el-button type="primary" @click="setRightDialogVisible">确 定</el-button>
                </span>
              </el-dialog>
            </div>
        </el-card>
    </div>
</template>

<script>
export default {
  data() {
    // 自定义验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      var EmailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (EmailReg.test(value)) {
        return callback()
      }
      return callback(new Error('请输入正确的邮箱'))
    }
    // 自定义验证手机号的规则
    var checkmobile = (rule, value, callback) => {
      var phoneReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]||17[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|19[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (phoneReg.test(value)) {
        return callback()
      }
      return callback(new Error('请输入正确的手机号'))
    }
    return {
      // 控制添加用户对话框的显示与隐藏
      dialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      editUserFormData: {},
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 4
      },
      // 获取到的用户列表
      userList: [],
      total: 0,
      addUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 控制角色分配对话框的显示隐藏
      setRoleDialogVisible: false,
      // 点击角色分配按钮获取到的用户信息
      userInfo: {},
      roleList: [],
      selectedRoleId: '',
      // 添加用户的表单验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.total = res.data.total
      this.userList = res.data.users
    },
    // 监听 pagesize 改变事件
    handleSizeChange(newpagesize) {
      console.log(1)
      this.queryInfo.pagesize = newpagesize
      this.getUserList()
    },
    // 监听 页码值改变事件
    handleCurrentChange(newpagenum) {
      this.queryInfo.pagenum = newpagenum
      this.getUserList()
    },
    // 监听用户状态改变事件
    async changeUserStatus(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听对话框关闭事件
    handleClose() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(async valied => {
        // eslint-disable-next-line no-useless-return
        if (!valied) return
        // 发起网络请求
        var { data: res } = await this.$http.post('users', this.addUserInfo)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 弹出编辑用户对话框
    async editDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('更新用户失败')
      this.editUserFormData = res.data
      // this.$message.success('更新用户成功')
      this.editDialogVisible = true
    },
    // 监听编辑对话框关闭重置表单
    editDialogClose() {
      this.$refs.EditFormRef.resetFields()
    },
    // 编辑用户
    editUserInfo() {
      this.$refs.EditFormRef.validate(async valied => {
        console.log(valied)
        // eslint-disable-next-line no-useless-return
        if (!valied) return
        const { data: res } = await this.$http.put('users/' + this.editUserFormData.id, {
          email: this.editUserFormData.email, mobile: this.editUserFormData.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('更新用户信息失败')
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('更新用户信息成功')
      })
    },
    // 删除用户
    async removeUserById(id) {
      const comfirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (comfirmResult !== 'confirm') {
        return this.$message('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 点击角色分配按钮显示 对话框
    async setRole(role) {
      this.setRoleDialogVisible = true
      this.userInfo = role
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      // this.$message.success('获取角色列表成功')
      // console.log(res)
    },
    // 点击确定按钮 分配角色
    async setRightDialogVisible() {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.getUserList()
      this.setRoleDialogVisible = false
      this.userInfo = {}
      this.selectedRoleId = ''
      this.$message.success('分配角色成功')
    }
  },
  created() {
    this.getUserList()
  },
  watch: {
    selectedRoleId: function(valNew) {
      console.log(valNew)
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
    margin-bottom: 15px;
}
.el-table {
  margin-top:15px;
}
</style>
